﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS_下发车辆信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoWMSCarInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_gz;


        public TMStoWMSCarInfoController(ILogger<TMStoWMSCarInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_gz = _configuration.GetConnectionString("WMSDbConnection_GZ");
            _logger = loggerFactory.CreateLogger<TMStoWMSCarInfoController>();
        }

        /// <summary>
        /// TMS_下发车辆信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostWMSAddCarInfo([FromBody] TMStoWMSCarInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            TMStoWMSCarInfoResponseDto re = new TMStoWMSCarInfoResponseDto();
            string waybill_no = strparm.waybill_no;
            string in_con = "";//目标WMS数据库
            try
            {
                if (waybill_no == "")
                {
                    strMsg = "fy_code must be not null";
                }
                if (strparm.factory_code == "")
                {
                    strMsg = "factory_code must be not null";
                }
                else
                {
                    if (strparm.factory_code.Contains("zh"))
                    {
                        in_con = con_zh;
                    }
                    else
                    {
                        if (strparm.factory_code.Contains("qh"))
                        {
                            in_con = con_qh;
                        }
                        else
                        {
                            if (strparm.factory_code.Contains("sc"))
                            {
                                in_con = con_yb;
                            }
                            else
                            {
                                if (strparm.factory_code.Contains("gz"))
                                {

                                }
                                else
                                {
                                    strMsg = "factory_code=<" + strparm.factory_code + "> not find ";
                                }                                
                            }
                        }
                    }
                }

                if (strMsg == "")
                {
                    //组件WMS
                    if (strparm.factory_code.Contains("gz"))
                    {
                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("waybill_no", waybill_no);//查询对应物流计划
                        DataTable fy_dt = MethodHelp.GetTableInfo("TMS0071", dic, con);//获取物流计划明细，订单数据源
                        if (fy_dt.Rows.Count>0)
                        {
                            //代工不做逻辑处理
                            if (fy_dt.Rows[0]["business_type"].ToString().Contains("代工"))
                            {

                            }
                            //非代工的逻辑需要处理
                            else
                            {
                                WMS_CarInfoInPutRequestDto data = new WMS_CarInfoInPutRequestDto();
                                WMS_CarInfoInPutHeaderDto header = new WMS_CarInfoInPutHeaderDto();
                                List<WMS_CarInfoInPutHeader> header_input = new List<WMS_CarInfoInPutHeader>();
                                dic = new Dictionary<string, string>(); //查询公用dic
                                dic.Add("waybill_no", waybill_no);//查询对应物流计划                           
                                DataTable sod_dt = MethodHelp.GetTableInfo("TMS0072", dic, con);//获取物流计划明细，订单数据源
                                if (sod_dt.Rows.Count > 0)
                                {
                                    List<WMS_CarInfoInPutDetails> details_input = new List<WMS_CarInfoInPutDetails>();
                                    //循环插入明细
                                    foreach (DataRow row in sod_dt.Rows)
                                    {
                                        details_input.Add(new WMS_CarInfoInPutDetails
                                        {
                                            logPlanNo = row["waybill_no"].ToString(),
                                            salesOrderNo = row["saleorder_no"].ToString(),
                                            cusAddress = row["delivery_address"].ToString(),
                                            cusContact = row["customer_contacts"].ToString() + ',' + row["contacts_tel"].ToString(),
                                            endCustomer = row["customer_name"].ToString()
                                        });
                                    }

                                    //添加到header
                                    if (details_input != null)
                                    {
                                        header_input.Add(new WMS_CarInfoInPutHeader
                                        {
                                            waybillNo = fy_dt.Rows[0]["waybill_no"].ToString(),
                                            driverName = fy_dt.Rows[0]["driver_name"].ToString(),
                                            carNo = fy_dt.Rows[0]["car_no"].ToString(),
                                            driverTel = fy_dt.Rows[0]["driver_tel"].ToString(),
                                            driverIdcard = fy_dt.Rows[0]["driver_idcard"].ToString(),
                                            carrierName = fy_dt.Rows[0]["carriername"].ToString(),
                                            details = details_input
                                        });
                                    }


                                }
                                else
                                {
                                    strMsg = "运单号=<" + waybill_no + "> 找不到对应明细信息!";
                                }

                                if (header_input != null)
                                {
                                    header.header = header_input;
                                }
                                if (header != null)
                                {
                                    data.data = header;
                                }


                                if (data != null)
                                {
                                    Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                    urldic.Add("function_description", "内部:组件WMS_车辆信息新增");//查看URL配置表地址描述
                                    DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                    if (url_dt.Rows.Count > 0)
                                    {
                                        string jsonText = JsonConvert.SerializeObject(data);
                                        var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                        WMS_CarInfoInPutResponseDto psp = JsonConvert.DeserializeObject<WMS_CarInfoInPutResponseDto>(reAgv);
                                        if (psp.code > 0)
                                        {
                                            strMsg = "WMS ERR:" + psp.message;
                                        }
                                    }
                                }
                            }                            
                        }
                        else
                        {
                            strMsg = "运单号=<" + waybill_no + "> 找不到对应主表信息!";
                        }
                    }
                    //晶硅WMS
                    else
                    {
                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("waybill_no", waybill_no);//查询对应物流计划
                        DataTable fy_dt = MethodHelp.GetTableInfo("TMS0079", dic, con);//获取物流计划明细，订单数据源
                        if (fy_dt.Rows.Count > 0)
                        {
                            strSqlList = new List<string>();
                            foreach (DataRow item in fy_dt.Rows)
                            {
                                dic = new Dictionary<string, string>();
                                dic.Add("factory_code", strparm.factory_code);
                                dic.Add("shippingorder_no", item["waybill_no"].ToString());
                                dic.Add("shipping_date", item["shipping_date"].ToString());
                                dic.Add("carrier_code", item["carrier_code"].ToString());
                                dic.Add("carrier_name", item["carriername"].ToString());
                                dic.Add("car_no", item["car_no"].ToString());
                                dic.Add("driver_name", item["driver_name"].ToString());
                                dic.Add("driver_tel", item["driver_tel"].ToString());
                                dic.Add("sales_order_no", "1301");
                                dic.Add("customer_code", item["customer_code"].ToString());
                                dic.Add("customer_name", item["customer_name"].ToString());
                                dic.Add("sales_order_line_id", "1301");
                                dic.Add("sales_order_line_no", "1.1");
                                dic.Add("material_code", item["material_code"].ToString());
                                dic.Add("material_name", item["material_name"].ToString());
                                dic.Add("material_amount", item["saleorder_qty"].ToString());
                                dic.Add("shipment_amount", item["ship_qty"].ToString());
                                dic.Add("start_address", item["shipping_address"].ToString());
                                dic.Add("target_address", item["delivery_address"].ToString());
                                dic.Add("receipt_man", item["customer_contacts"].ToString());
                                dic.Add("receipt_tel", item["contacts_tel"].ToString());
                                dic.Add("plan_id", item["plan_no"].ToString());
                                dic.Add("create_by", item["created_by"].ToString());
                                dic.Add("crm_no", item["plan_no"].ToString());
                                dic.Add("receipt_no", item["waybill_no"].ToString() + item["saleorder_no"].ToString()+ item["saleorderline_no"].ToString());
                                dic.Add("address_id", "");
                                string strSQL = MethodHelp.GetTranSQL("TMS0080", dic, con);
                                if (strSQL.Trim() != "")
                                {
                                    strSqlList.Add(strSQL.ToString());
                                }
                                else
                                {
                                    strMsg = "TMS0080 Parameter conversion failed";
                                }
                            }

                            if (strMsg == "")
                            {
                                if (strSqlList.Count > 0)
                                {
                                    bool A = DB.ExecuteNoQueryTran(strSqlList, in_con);
                                    if (A)
                                    {


                                    }
                                    else
                                    {
                                        strMsg =waybill_no+ "--数据库插入失败，请联系管理原测试！";
                                    }


                                }
                            }
                        }
                        else
                        {

                        }
                    }                  
                                    
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
